<template>
  <view class="swiperImage">
    <!-- <swiper
      class="swiperImage-container"
      circular
      :indicator-dots="indicatorDots"
      :autoplay="autoplay"
      :interval="interval"
      :duration="duration"
    >
      <swiper-item v-for="item in background" :key="item">
        <image class="imageStyle" :mode="'aspectFit'" :src="item"></image>
      </swiper-item>
    </swiper> -->

    <z-swiper
      ref="zSwiper"
      class="swiperImage-container"
      v-model="swiperData"
      :options="options"
      @slideChange="onChange"
    >
      <z-swiper-item
        class="swiperItem"
        v-for="(item, index) in swiperData"
        :key="index"
      >
        <!-- <image ref="img" class="imageStyle" :src="item.image" mode="aspectFit">
        </image> -->
        <canvas
          hidpi
          style="height: 431rpx; width: 100%"
          :canvas-id="'secondCanvas' + index"
          :id="'secondCanvas' + index"
          @error="canvasIdErrorCallback"
          @touchend="canvasClickHandle"
        ></canvas>
      </z-swiper-item>
    </z-swiper>
    <view class="hideCanvass">
      <canvas
        hidpi
        :style="`height: ${sourceImageHeight}px; width: ${sourceImageWidth}px`"
        canvas-id="previewImage"
        id="previewImage"
      ></canvas>
    </view>
  </view>
</template>

<script>
import Vue from "vue";
export default Vue.extend({
  props: ["swiperData", "boxSwitch"],
  data() {
    return {
      options: {
        centeredSlides: true,
        // centeredSlidesBounds: true,
        spaceBetween: 14,
        slidesPerView: 1.15
      },
      swiperIndex: 0,
      indicatorDots: false,
      autoplay: false,
      interval: 2000,
      duration: 500,
      canvasInfo: {},
      sourceImageWidth: 1440,
      sourceImageHeight: 900
      // tempImage: ""
    };
  },
  mounted() {
    this.$nextTick(async () => {
      let { width, height } = await this.queryCanvasInfo();
      this.canvasInfo = { width: width * 0.85, height };
      this.swiperData.forEach((ele, index) => {
        this.$emit("collectData", {
          dataList: JSON.parse(ele.originData),
          index
        });
        this.drawImage(ele.image, index, ele);
      });
    });
  },
  methods: {
    onChange(i) {
      this.swiperIndex = i.activeIndex;
      this.$emit("swiperDataIndex", this.swiperIndex);
      this.$emit("selectIndex", 0);
      if (this.swiperData[this.swiperIndex].data.length > 0) {
        this.drawImage(
          this.swiperData[this.swiperIndex].image,
          this.swiperIndex,
          this.swiperData[this.swiperIndex]
        );
      }
    },
    async queryCanvasInfo() {
      return new Promise((resolve, reject) => {
        const query = uni.createSelectorQuery().in(this);
        query
          .select("canvas")
          .boundingClientRect((data) => {
            resolve(data);
          })
          .exec();
      });
    },
    async drawImage(image, index, item) {
      let ctx = uni.createCanvasContext("secondCanvas" + index);
      this.sourceImageWidth = item.width;
      this.sourceImageHeight = item.height;
      ctx.drawImage(image, 0, 0, this.canvasInfo.width, this.canvasInfo.height);
      if (!this.boxSwitch) {
        ctx.draw();
        return false;
      }
      if (item.data.length === 0) {
        ctx.draw(true, () => {
          this.postApi(ctx, index, item);
        });
      } else {
        this.drawBox(ctx, item.data);
      }
    },
    drawBox(ctx, data, appoint = 0, previewImage = false) {
      let xZoom = 1;
      let yZoom = 1;
      let color = "#0AB679";
      let selectColor = "#0091FF";
      let abnormalColor = "#D53939";
      ctx.lineWidth = 3;
      ctx.setFillStyle("#ffffff");
      ctx.setFontSize(15);
      ctx.shadowColor = "#333";
      ctx.shadowBlur = 2;
      ctx.shadowOffsetX = 2;
      if (!previewImage) {
        ctx.lineWidth = 1;
        xZoom = this.canvasInfo.width / this.sourceImageWidth;
        yZoom = this.canvasInfo.height / this.sourceImageHeight;
        ctx.setFontSize(7);
      }

      data.forEach((element, index) => {
        if ("type" in element) {
          ctx.setStrokeStyle(appoint === index ? selectColor : abnormalColor);
        } else {
          ctx.setStrokeStyle(appoint === index ? selectColor : color);
        }
        if ("name" in element) {
          let text = element.name === "image_vague" ? "未入库" : element.name;
          ctx.fillText(
            text,
            element.position[0] * xZoom,
            element.position[1] * yZoom - 2,
            (element.position[2] - element.position[0]) * xZoom - 5
          );

          // #405680
        }
        ctx.strokeRect(
          element.position[0] * xZoom,
          element.position[1] * yZoom,
          (element.position[2] - element.position[0]) * xZoom,
          (element.position[3] - element.position[1]) * yZoom
        );
      });
      if (!previewImage) ctx.draw();
    },

    postApi(ctx, index, item) {
      uni.showLoading({
        title: "识别中"
      });
      let image = item.image.split("data:image/jpeg;base64,")[1];

      uni.request({
        url: "api/cv/image/lw/predict", //仅为示例，并非真实接口地址。
        method: "POST",
        data: {
          image: image,
          image_type: 1,
          threshold: 0.35
        },
        header: {},
        success: (res) => {
          let dataList = JSON.parse(res.data.data);
          // let data = this.dataHandle(dataList);
          this.$emit("collectData", {
            dataList,
            index
          });
          this.$emit("swiperData", { index, dataList });
          ctx.drawImage(
            item.image,
            0,
            0,
            this.canvasInfo.width,
            this.canvasInfo.height
          );
          if (this.boxSwitch) {
            this.drawBox(ctx, data);
          }
          uni.hideLoading();
        }
      });
      // uni.canvasToTempFilePath(
      //   {
      //     x: 0,
      //     y: 0,
      //     width: this.sourceImageWidth,
      //     height: this.sourceImageHeight,
      //     destWidth: this.sourceImageWidth,
      //     destHeight: this.sourceImageHeight,
      //     fileType: "jpg",
      //     canvasId: "tempCanvas",
      //     success: (res) => {
      //       // 在H5平台下，tempFilePath 为 base64
      //       // that.imagesrc = res.tempFilePath;
      //       console.log(res.tempFilePath);
      //       let image = res.tempFilePath.split("data:image/jpeg;base64,")[1];
      //       uni.request({
      //         url: "api/cv/image/lw/predict", //仅为示例，并非真实接口地址。
      //         method: "POST",
      //         data: {
      //           image: image,
      //           image_type: 1,
      //           threshold: 0.9
      //         },
      //         header: {},
      //         success: (res) => {
      //           let dataList = JSON.parse(res.data.data);
      //           let data = this.dataHandle(dataList);
      //           this.$emit("collectData", {
      //             data: this.collectData(dataList),
      //             index
      //           });
      //           this.$emit("swiperData", { index, data });
      //           ctx.drawImage(
      //             "data:image/jpeg;base64," + image,
      //             0,
      //             0,
      //             this.canvasInfo.width,
      //             this.canvasInfo.height
      //           );
      //           if (this.boxSwitch) {
      //             this.drawBox(ctx, data);
      //           }
      //           uni.hideLoading();
      //         }
      //       });
      //     }
      //   },
      //   this
      // );
    },
    dataHandle(dataList) {
      let data = dataList.casePositionList;
      let arr = [];
      dataList.lostPricePositionList.forEach((element) => {
        let target = true;
        data.forEach((item) => {
          if (item.position.toString() === element.toString()) {
            item["type"] = "lostPriceTag";
            target = false;
          }
        });
        if (target) {
          arr.push({
            position: element,
            rectColor: "#D53939",
            type: "lostPriceTag"
          });
        }
      });
      dataList.lostCasePositionList.forEach((element) => {
        let target = true;
        data.forEach((item) => {
          if (item.position.toString() === element.toString()) {
            item["type"] = "lostPriceTag";
            target = false;
          }
        });
        if (target) {
          arr.push({
            position: element,
            rectColor: "#D53939",
            type: "lostCase"
          });
        }
      });
      return [...data, ...arr];
    },
    collectData(dataList) {
      let lineCount = 0;
      let brandCount = 0;
      let brandTempArr = [];
      let typeTempArr = [];
      let boxCount = dataList.casePositionList.length;
      let tagCount = dataList.casePositionList.length;
      let boxAskew = dataList.askewCasePositionList.length;
      let boxLost = dataList.lostCasePositionList.length;
      let tagLost = dataList.lostPricePositionList.length;
      let brandLoadRate = [];
      let typeLoadRate = [];

      dataList.casePositionList.forEach((element) => {
        // let brand =smk[0]
        // let type=
        if (element.row > lineCount) lineCount = element.row;
        if (element.name) {
          let smk = element.name.split("_");
          brandTempArr.push(smk[0]);
          typeTempArr.push(element.name);
        }
      });
      let rateCompute = (tempArr, index, isSplit = true) => {
        let arr = [];
        tempArr.forEach((name) => {
          let count = 0;
          dataList.casePositionList.forEach((item) => {
            if (item.name) {
              if (isSplit) {
                let smk = item.name.split("_");
                if (name === smk[index]) {
                  count++;
                }
              } else {
                if (name === item.name) {
                  count++;
                }
              }
            }
          });
          arr.push({
            name,
            count,
            rateCount:
              Math.floor((count / dataList.casePositionList.length) * 10000) /
              100
          });
        });
        return arr;
      };
      let tempArr = [...new Set(brandTempArr)];
      brandCount = tempArr.length;

      brandLoadRate = rateCompute(tempArr, 0);
      tempArr = [...new Set(typeTempArr)];
      typeLoadRate = rateCompute(tempArr, 1, false);
      return {
        lineCount,
        brandCount,
        boxCount,
        tagCount,
        boxAskew,
        boxLost,
        tagLost,
        brandLoadRate,
        typeLoadRate
      };
    },
    canvasClickHandle(event) {
      let { x, y } = event.changedTouches[0];
      let xZoom = this.canvasInfo.width / this.sourceImageWidth;
      let yZoom = this.canvasInfo.height / this.sourceImageHeight;
      let forData = this.swiperData[this.swiperIndex].data;
      let ctx = uni.createCanvasContext(
        "secondCanvas" + this.swiperIndex,
        this
      );
      for (let i = 0; i < forData.length; i++) {
        let element = forData[i];
        let x1 = element.position[0] * xZoom;
        let y1 = element.position[1] * yZoom;
        let x2 = (element.position[2] - element.position[0]) * xZoom;
        let y2 = (element.position[3] - element.position[1]) * yZoom;
        // let nextX1 = forData[i + 1].position[0] * xZoom;
        // let nextX2 =
        //   (forData[i + 1].position[2] - forData[i + 1].position[0]) * xZoom;
        if (x >= x1 && x <= x2 + x1 && y >= y1 && y <= y2 + y1) {
          // if (x < nextX1 && x > nextX2) {
          ctx.drawImage(
            this.swiperData[this.swiperIndex].image,
            0,
            0,
            this.canvasInfo.width,
            this.canvasInfo.height
          );
          this.$emit("selectIndex", i);
          this.drawBox(ctx, forData, i);
          return false;
          // }

          // return false;
        }
      }
    },

    async onFullScreen(appoint = 0) {
      return new Promise((resolve) => {
        let currData = this.swiperData[this.swiperIndex];
        let ctx = uni.createCanvasContext("previewImage");
        ctx.drawImage(currData.image, 0, 0, currData.width, currData.height);
        this.drawBox(ctx, currData.data, 0, true);
        ctx.draw(true, () => {
          uni.canvasToTempFilePath(
            {
              x: 0,
              y: 0,
              width: this.sourceImageWidth,
              height: this.sourceImageHeight,
              destWidth: this.sourceImageWidth,
              destHeight: this.sourceImageHeight,
              fileType: "jpg",
              canvasId: "previewImage",
              success: (res) => {
                // 在H5平台下，tempFilePath 为 base64
                // that.imagesrc = res.tempFilePath;
                resolve(res.tempFilePath);
              }
            },
            this
          );
        });
      });
    }
  },
  watch: {
    swiperData(newVal, oldVal) {
      let last = newVal.length - 1;
      if (newVal[last].data.length > 0) return false;
      this.$nextTick(() => {
        this.drawImage(newVal[last].image, last, newVal[last]);
        setTimeout(() => {
          this.$refs.zSwiper.swiper.slideTo(last, 500, false);
        }, 500);
        // this.options.initialSlide = last
      });
    },
    boxSwitch(newVal) {
      // console.log(this.swiperIndex, this.swiperIndex);
      // this.swiperIndex[this.swiperIndex].data;
      this.drawImage(
        this.swiperData[this.swiperIndex].image,
        this.swiperIndex,
        this.swiperData[this.swiperIndex]
      );
    }
  }
});
</script>

<style lang="scss" scoped>
.swiperImage {
  // padding: 0 29rpx;
  &-container {
    height: 431rpx;
    width: 100%;
    .swiperItem {
      position: relative;
    }
    .imageStyle {
      width: 1024px;
      height: 720px;
    }
    canvas {
    }
  }
}
.hideCanvass {
  width: 0;
  height: 0;
  overflow: hidden;
}
</style>
